package com.goldmantis.alitrip.common;

import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:Shmily
 * @Description:
 * @Date:Create in 12:40 2018/2/11
 */
public class ReturnMessage {

    /**
     * 返回结果代码
     */
    @ApiModelProperty("返回结果代码")
    private Integer businessCode;

    /**
     * 响应错误消息
     */
    @ApiModelProperty("响应错误消息")
    private String errorMessage;

    /**
     * 处理结果
     */
    @ApiModelProperty("处理结果")
    private Object result;

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    /**
     * 其他信息
     */
    @ApiModelProperty("其他信息")
    private Map<String,Object> otherInfo=new HashMap();


    public Integer getBusinessCode() {
        return businessCode;
    }

    public void setBusinessCode(Integer businessCode) {
        this.businessCode = businessCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public Map<String, Object> getOtherInfo() {
        return otherInfo;
    }

    public void setOtherInfo(Map<String, Object> otherInfo) {
        this.otherInfo = otherInfo;
    }


    public static ReturnMessage success(Object result){
        ReturnMessage returnMessage=new ReturnMessage();
        returnMessage.setBusinessCode(0);
        returnMessage.setResult(result);

        return returnMessage;
    }

    public static ReturnMessage failure(Exception ex){
        ReturnMessage returnMessage=new ReturnMessage();
        returnMessage.setBusinessCode(-1);
        if(!StringUtils.isEmpty(ex.getMessage())) {
            returnMessage.setErrorMessage(ex.getMessage());
        }
        else {
            StringWriter stringWriter=new StringWriter();
            PrintWriter printWriter=new PrintWriter(stringWriter,true);
            ex.printStackTrace(printWriter);
            printWriter.flush();
            stringWriter.flush();
            returnMessage.setErrorMessage(stringWriter.toString());
        }
        return returnMessage;
    }

    public static ReturnMessage failure(String errorMessage){
        ReturnMessage returnMessage=new ReturnMessage();
        returnMessage.setBusinessCode(-1);
        returnMessage.setErrorMessage(errorMessage);

        return returnMessage;
    }

    public ReturnMessage add(String key,Object value){
        this.getOtherInfo().put(key,value);
        return this;
    }
}
